from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import elevy_stamp as schemas
from app.database.models.erp import ElevyStamp, PackageOrder
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.ElevyStamp])
def list_elevy_stamps(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    package_order_id: Optional[int] = None,
    reference_no: Optional[str] = None,
    status: Optional[str] = None,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取印花税记录列表"""
    try:
        query = db.query(ElevyStamp)
        
        # 根据用户角色和工作区过滤
        if current_user.role == "agent":
            # agent只能查看自己工作区的记录
            query = query.filter(ElevyStamp.work_area_id == current_user.workarea_id)
        elif current_user.role != "admin":
            raise HTTPException(
                status_code=403,
                detail="Not enough permissions to view elevy stamps"
            )
        
        # 添加过滤条件
        if package_order_id:
            query = query.filter(ElevyStamp.package_order_id == package_order_id)
        if reference_no:
            query = query.filter(ElevyStamp.ReferenceNo.like(f"%{reference_no}%"))
        if status:
            query = query.filter(ElevyStamp.ElevyStampStatus == status)
            
        # 添加排序和分页
        query = query.order_by(ElevyStamp.ElevyStampCreateTime.desc())
        stamps = query.offset(skip).limit(limit).all()
        
        return stamps
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching elevy stamps: {str(e)}"
        )

@router.post("/", response_model=schemas.ElevyStamp)
def create_elevy_stamp(
    *,
    db: Session = Depends(deps.get_db),
    stamp_in: schemas.ElevyStampCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的印花税记录"""
    try:
        # 使用当前用户的工作区ID
        stamp_data = stamp_in.dict()
        stamp_data["work_area_id"] = current_user.workarea_id
        
        # 检查关联的打包订单
        package_order = db.query(PackageOrder).filter(
            PackageOrder.ID == stamp_data["package_order_id"]
        ).first()
        
        if not package_order:
            raise HTTPException(
                status_code=404,
                detail="Package order not found"
            )
            
        if package_order.work_area_id != current_user.workarea_id:
            raise HTTPException(
                status_code=403,
                detail="Cannot create elevy stamp for package order from different work area"
            )
            
        # 设置打包订单标题
        stamp_data["package_order_title"] = package_order.title

        stamp = ElevyStamp(**stamp_data)
        db.add(stamp)
        db.commit()
        db.refresh(stamp)
        return stamp
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{stamp_id}", response_model=schemas.ElevyStamp)
def get_elevy_stamp(
    *,
    db: Session = Depends(deps.get_db),
    stamp_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取单个印花税记录"""
    try:
        stamp = db.query(ElevyStamp).filter(ElevyStamp.ID == stamp_id).first()
        if not stamp:
            raise HTTPException(status_code=404, detail="Elevy stamp not found")
            
        # 检查权限
        if current_user.role != "admin" and stamp.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")
            
        return stamp
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{stamp_id}", response_model=schemas.ElevyStamp)
def update_elevy_stamp(
    *,
    db: Session = Depends(deps.get_db),
    stamp_id: int,
    stamp_in: schemas.ElevyStampUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新印花税记录"""
    try:
        stamp = db.query(ElevyStamp).filter(ElevyStamp.ID == stamp_id).first()
        if not stamp:
            raise HTTPException(status_code=404, detail="Elevy stamp not found")

        # 检查权限
        if current_user.role != "admin" and stamp.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新记录
        update_data = stamp_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(stamp, field, value)

        db.add(stamp)
        db.commit()
        db.refresh(stamp)
        return stamp
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{stamp_id}", response_model=schemas.ElevyStamp)
def delete_elevy_stamp(
    *,
    db: Session = Depends(deps.get_db),
    stamp_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除印花税记录"""
    try:
        stamp = db.query(ElevyStamp).filter(ElevyStamp.ID == stamp_id).first()
        if not stamp:
            raise HTTPException(status_code=404, detail="Elevy stamp not found")

        # 检查权限
        if current_user.role != "admin" and stamp.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        db.delete(stamp)
        db.commit()
        return stamp
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 